package net.maku.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import io.jsonwebtoken.Claims;
import jodd.util.StringUtil;
import lombok.AllArgsConstructor;
import net.maku.bean.dto.WxUserDto;
import net.maku.bean.model.MyException;
import net.maku.bean.param.WeixinAppParam;
import net.maku.bean.param.WeixinParam;
import net.maku.bean.vo.UserTokenVo;
import net.maku.bean.vo.WebUserVO;
import net.maku.entity.WebUserEntity;
import net.maku.utils.InviteCodeGenerator;
import net.maku.utils.JsonUtils;
import net.maku.utils.MyBeanUtils;
import net.maku.utils.NewJwtUtils;
import net.maku.utils.TokenUtils;
import net.maku.utils.WeChatUtil;

@Service
@AllArgsConstructor
public class LoginInfoServiceImpl {

	public void updateHeadimg( WeixinParam query ) {
		WebUserEntity entity = TokenUtils.getUserBean();
		entity = webUserServiceImpl.getById(entity.getId());
		entity.setAvatar(query.getHeaderImage());
		webUserServiceImpl.updateById(entity);
    }
	
	public void updateNickName( WeixinParam query ) {
		WebUserEntity entity = TokenUtils.getUserBean();
		entity = webUserServiceImpl.getById(entity.getId());
		entity.setUsername(query.getNickName());
		webUserServiceImpl.updateById(entity);
    }
	
	public void updateProxy( String phone ) {
		QueryWrapper<WebUserEntity> wrapper = new QueryWrapper<WebUserEntity>();
        wrapper.eq("mobile", phone );
        List<WebUserEntity> list = webUserServiceImpl.list(wrapper);
        if( list.size()<=0 ) {
        	throw new MyException("修改渠道用户失败");
        }
        WebUserEntity entity = list.get(0);
        entity.setIsproxy(1);
        webUserServiceImpl.updateById(entity);
    }

	public UserTokenVo userLogin( WeixinParam query, String phone ) {
    	QueryWrapper<WebUserEntity> wrapper = new QueryWrapper<WebUserEntity>();
        wrapper.eq("openid", query.getOpenid() );
        List<WebUserEntity> list = webUserServiceImpl.list(wrapper);
        if( list.size()<=0 ) {
        	throw new MyException("用户登录异常");
        }
        WebUserEntity userBean = list.get(0);
        userBean.setAvatar(query.getHeaderImage());
        userBean.setUsername(query.getNickName());
        userBean.setMobile(phone);
        webUserServiceImpl.updateById(userBean);
        Map<String,Object> claimsmap = new HashMap<>();
        userBean.setAvatar("");
    	claimsmap.put("user", JsonUtils.toJson(userBean) );
    	UserTokenVo vo = new UserTokenVo();
    	vo.setToken(NewJwtUtils.generateTokenByDeviceid( claimsmap, query.getDeviceid() ));
    	vo.setRefcode(userBean.getRefcode());
    	return vo;
    }
	
	
	public UserTokenVo userAppLogin( WeixinAppParam query ) {
		String str = WeChatUtil.getWxUserInfo( query.getAccessToken(), query.getOpenid() );
		System.out.println(str);
		WxUserDto dto = JsonUtils.fromJson(str, WxUserDto.class);
		System.out.println(dto.toString());
		System.out.println(query.toString());
		if( !dto.getOpenid().equals(query.getOpenid()) ) {
			throw new MyException("用户登录异常");
		}
		
		WebUserEntity userBean = new WebUserEntity();
		userBean.setUnionid(dto.getUnionid());
		userBean.setUsername(dto.getNickname());
		userBean.setAvatar(dto.getHeadimgurl());
		userBean.setDeviceid(query.getDeviceid());
		userBean.setAppopenid(dto.getOpenid());
		QueryWrapper<WebUserEntity> wrapper = new QueryWrapper<WebUserEntity>();
        wrapper.eq("unionid", userBean.getUnionid() );
        List<WebUserEntity> list = webUserServiceImpl.list(wrapper);
        if( list.size()<=0 ) {
        	userBean.setCountnum(0);
        	userBean.setStatus(1);
        	userBean.setRefcode(  getUserInviteCode() );
        	userBean.setBrefcode( query.getRefcode()  );
        	webUserServiceImpl.save(userBean);
        }else {
        	userBean = list.get(0);
        	userBean.setAppopenid(dto.getOpenid());
        	webUserServiceImpl.updateById(userBean);
        }

        Map<String,Object> claimsmap = new HashMap<>();
        userBean.setAvatar("");
    	claimsmap.put("user", JsonUtils.toJson(userBean) );
    	UserTokenVo vo = new UserTokenVo();
    	vo.setToken(NewJwtUtils.generateTokenByDeviceid( claimsmap, query.getDeviceid() ));
    	if( userBean.getIsproxy()==1) {
    		vo.setRefcode(userBean.getRefcode());
    	}
    	return vo;
    	
	}
	
 

    public UserTokenVo userLogin( WebUserEntity userBean, WeixinParam query ) {
    	QueryWrapper<WebUserEntity> wrapper = new QueryWrapper<WebUserEntity>();
        //wrapper.eq("openid", userBean.getOpenid() );
    	wrapper.eq("unionid", userBean.getUnionid() );
        List<WebUserEntity> list = webUserServiceImpl.list(wrapper);
        if( list.size()<=0 ) {
        	userBean.setCountnum(0);
        	userBean.setStatus(1);
        	userBean.setRefcode(  getUserInviteCode() );
        	userBean.setBrefcode( query.getRefcode()  );
        	webUserServiceImpl.save(userBean);
        	//修改用户推荐人数
        	if( StringUtils.isNotBlank( query.getRefcode() ) ) {
        		wrapper = new QueryWrapper<WebUserEntity>();
        		wrapper.eq("refcode", query.getRefcode() );
        		System.out.println(  query.getRefcode() );
        		WebUserEntity tuser = webUserServiceImpl.getOne(wrapper);
        		System.out.println( tuser.toString() );
        		tuser.setReferrals(tuser.getReferrals()+1);  
        		webUserServiceImpl.updateById(tuser);
        	}
        }else {
        	userBean = list.get(0);
        	userBean.setOpenid( userBean.getOpenid() );
        	webUserServiceImpl.updateById(userBean);
        }
        /*
        //没有手机号，不返回token
        if( StringUtil.isBlank(userBean.getMobile())) {
    	   return new UserTokenVo();
        }*/
       
        Map<String,Object> claimsmap = new HashMap<>();
        userBean.setAvatar("");
    	claimsmap.put("user", JsonUtils.toJson(userBean) );
    	UserTokenVo vo = new UserTokenVo();
    	vo.setToken(NewJwtUtils.generateTokenByDeviceid( claimsmap, query.getDeviceid() ));
    	if( userBean.getIsproxy()!=null && userBean.getIsproxy()==1) {
    		vo.setRefcode(userBean.getRefcode());
    	}
    	return vo;
    }
    
    public String getUserInviteCode() {
    	QueryWrapper<WebUserEntity> wrapper = new QueryWrapper<WebUserEntity>();
    	String code = InviteCodeGenerator.genCode();
    	List<WebUserEntity> list = webUserServiceImpl.list(wrapper);
    	if( list.size()>0 ) {
    		return code;
        }
    	while(true) {
    		code = InviteCodeGenerator.genCode();
    		wrapper.eq("refcode", code );
    		list = webUserServiceImpl.list(wrapper);
            if( list.size()<=0 ) {
            	break;
            }
    	}
    	return code;
    }

    public WebUserVO getUserInfo( int type ) {
    	WebUserEntity entity = TokenUtils.getUserBean();
    	if(type!=0) {
    		entity = webUserServiceImpl.getById(entity.getId());
    	}
    	//System.out.println(entity.toString());
    	WebUserVO vo = WebUserVO.builder()
    			.avatar(entity.getAvatar())
    			.mobile( DesensitizedUtil.mobilePhone(entity.getMobile())  )
    			.countnum( entity.getCountnum() )
    			.username( entity.getUsername() )
    			.gender(entity.getGender())
    			.refcode(  entity.getRefcode())
    			.isproxy(  entity.getIsproxy())
    			.refcode(  entity.getRefcode())
    			.brefcode( entity.getBrefcode() )
    			.referrals( entity.getReferrals() )
    			.income( (entity.getIncome()*1.0/100)+"" )
    			.build();
    	
    	return vo;
    }
    
    
    public UserTokenVo flushToken() {
    	WebUserEntity entity = TokenUtils.getUserBean();
    	String deviceid = entity.getDeviceid();
    	entity = webUserServiceImpl.getById(entity.getId());
    	UserTokenVo vo = new UserTokenVo();
    	Map<String,Object> claimsmap = new HashMap<>();
    	entity.setAvatar("");
    	claimsmap.put("user", JsonUtils.toJson(entity) );
    	vo.setToken(NewJwtUtils.generateTokenByDeviceid( claimsmap, deviceid ));
    	vo.setRefcode(entity.getRefcode());
    	return vo;
    }


    
    @Autowired
    WebUserServiceImpl        webUserServiceImpl;
    //@Autowired
    //WebPayRecordServiceImpl   webPayRecordServiceImpl;
    //@Autowired
    //WebTradeRecordServiceImpl webTradeRecordServiceImpl;
}
